import { Message } from 'element-ui';
import axios from 'axios'
import { checkloginServer } from "../api/user";

export default {
  state: {
    userState: {
      isLogin: false,
      token: undefined,
      userData: {
        username: "未知",
        userId: "",
        authority: 0, //0普通用户，1管理员
      }
    },
    interceptor: undefined,
  },
  mutations: {
    setUserState(state, params) {
      Object.keys(params).forEach(key => {
        state.userState[key] = params[key];
      });
    },
    setInterceptorState(state, interceptor) {
      state.interceptor = interceptor;
    }
  },
  actions: {
   
    setInterceptors({ commit, state }, token_val) {
      let token = "";
      if (!!token_val) {
        token = token_val;
        localStorage.setItem("token", token);
      } else {
        token = localStorage.getItem("token");
      }
      const hasToken = !!token;
      axios.interceptors.request.eject(state.interceptor);
      if (hasToken) {
        commit('setUserState', { token });
        commit('setInterceptorState', axios.interceptors.request.use(
          config => {
            config.headers.Authorization = "Bearer " + token;
            return config;
          },
          err => Promise.reject(err)))
      };
    },
    exitSystemAction({ commit, state }) {
      localStorage.removeItem("token");
      commit('setUserState', { isLogin: false });
      axios.interceptors.request.eject(state.interceptor);
      Message({
        type: 'success',
        message: '成功退出系统',
      });
    },
 
}
}
